import Vue from 'vue'
import Router from 'vue-router'
import home from '../components/home'
import login from '../components/login'
import register from '../components/register'
import searchList from '../components/searchList'
import movieDetail from '../components/common/movieDetail'
import historyList from '../components/historyList'
import admin from '../components/admin'
import favourite from '../components/favourite'
import movieManager from '../components/movieManager'
import userManager from '../components/userManager'
Vue.use(Router)
const original = Router.prototype.push
Router.prototype.push = function push (location) {
  return original.call(this, location).catch(err => err)
}
const routers = new Router({
  mode: 'history',
  linkActiveClass: 'active',
  routes: [
    {
      path: '/',
      name: 'gate',
      component: home
    },
    {
      path: '/home',
      name: 'home',
      component: home,
      children: [
        {
          path: 'search',
          name: 'searchList',
          component: searchList
        },
        {
          path: 'movieDetail',
          name: 'movieDetail',
          component: movieDetail
        },
        {
          path: 'historyList',
          name: 'historyList',
          component: historyList
        },
        {
          path: 'favourite',
          name: 'favourite',
          component: favourite
        }
      ]
    },
    {
      path: '/admin',
      name: 'admin',
      component: admin,
      children: [
        {
          path: 'movieManager',
          name: 'movieManager',
          component: movieManager
        },
        {
          path: 'userManager',
          name: 'userManager',
          component: userManager
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: login,
      meta: {
        requiresAuth: true
      }
    },
    {
      path: '/register',
      name: 'register',
      component: register,
      meta: {
        requiresAuth: true
      }
    }
  ]
})
// 注册全局钩子用来拦截导航
routers.beforeEach((to, from, next) => {
  // 获取store里面的token
  let token = routers.app.$cookies.get('token')
  // 判断要去的路由有没有requiresAuth
  if (to.meta.requiresAuth) {
    next()
  } else {
    if (token) {
      next()
    } else {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将刚刚要去的路由path（却无权限）作为参数，方便登录成功后直接跳转到该路由
      })
    }
  }
})

export default routers
